<template>
  <div>
    <div class="equip-wrap-common">
      <div style="padding: 16px 0 24px 0">
        <px-button type="primary" icon="ArrowLeft" @click="handleManage">返回</px-button>
      </div>
      <px-scrollbar class="form-scrollBar">
        <px-form ref="formRef" :rules="rules" :model="formValue" label-width="110px">
          <px-form-item label="公告标题" prop="title" style="width: 380px">
            <px-input
              v-model="formValue.title"
              clearable
              placeholder="请输入公告标题"
              maxlength="50"
              @blur="formValue.title = $event.target.value.trim()"
            />
          </px-form-item>
          <px-form-item label="公告内容" prop="content">
            <ReEditor ref="editorRef" v-model="formValue.content" placeholder="请输入公告内容" />
          </px-form-item>
          <px-form-item label="发布范围" prop="deptIds" style="width: 380px">
            <px-tree-select
              ref="treeRef"
              v-model="formValue.deptIds"
              :default-expanded-keys="formValue.deptIds"
              style="width: 100%"
              :data="deptData"
              filterable
              clearable
              multiple
              show-checkbox
              check-strictly
              node-key="deptId"
              :props="defaultProps"
              placeholder="请选择发布范围"
              :render-after-expand="true"
              :collapse-tags="true"
              :collapse-tags-tooltip="true"
              :max-collapse-tags="3"
            >
              <template #default="scope">
                <div class="option-flex-row">
                  {{ scope.data.deptName
                  }}<span v-if="scope?.data?.children?.length > 0" style="color: gray" @click.stop="handleClickAll(scope)">全部</span>
                </div>
              </template>
            </px-tree-select>
          </px-form-item>
          <px-form-item label="公示到期时间" prop="expireTime" style="width: 380px">
            <px-date-picker
              :disabled-date="disabledDate"
              style="width: 100%"
              v-model="formValue.expireTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择公示到期时间"
            />
          </px-form-item>
        </px-form>
      </px-scrollbar>
      <div class="info-form-btns">
        <px-button @click="handleManage">取消</px-button>
        <px-button type="primary" :loading="submitLoading" @click="handleSubmit(formRef)">保存</px-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { createAnnouncement, getAnnouncement, listDeptOptionTree, updateAnnouncement } from "@/api/bench";
import ReEditor from "@/components/ReEditor/index.vue";
import { cloneDeep } from "@pureadmin/utils";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
const editorRef = ref();
const rules = {
  title: {
    required: true,
    message: "值不能为空",
    trigger: "blur"
  },
  content: {
    required: true,
    message: "值不能为空",
    trigger: "blur",
    validator: (rule: any, value: any, callback: any) => {
      const content = editorRef.value.isWangEditorText();
      if (content) {
        callback();
      } else {
        callback(new Error("值不能为空"));
      }
    }
  },
  deptIds: {
    required: true,
    message: "值不能为空",
    trigger: "blur"
  },
  expireTime: {
    required: true,
    message: "值不能为空",
    trigger: "blur"
  }
};
const router = useRouter();
const route = useRoute();
const formRef = ref();
const deptData = ref();
const treeRef = ref();
const submitLoading = ref(false);
const defaultProps = {
  children: "children",
  label: "deptName"
};
let formDataTmpl = {
  title: "",
  content: "",
  deptIds: ""
};
const formValue = ref(cloneDeep(formDataTmpl));
onMounted(() => {
  queryData();
});
const disabledDate = (time: Date) => {
  return time.getTime() + 3600 * 1000 * 24 < Date.now();
};
const queryData = async () => {
  deptData.value = await listDeptOptionTree();
  const { id: routeId, serialNumber } = route.query;
  if (routeId) {
    const { id, title, content, publishRange, expireTime }: any = await getAnnouncement({ id: routeId, serialNumber });
    formValue.value = {
      id,
      title,
      content,
      expireTime,
      deptIds: publishRange?.split(",")?.map(item => Number(item))
    };
  }
};
//reset表单
const resetForm = () => {
  if (!formRef?.value) return;
  formRef.value.resetFields();
};
// 返回公告管理
const handleManage = () => {
  PxMessageBox.confirm("确定取消已录入的内容返回上一页吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    router.push("/all/bench/task/announcement/manage");
  });
};
const getAllTag = (ids, data) => {
  ids.push(data.deptId);
  if (data?.children?.length > 0) {
    data.children.forEach(item => {
      getAllTag(ids, item);
    });
  }
};
// 点击全部
const handleClickAll = scope => {
  const { deptIds } = formValue.value;
  const ids = [];
  const new_deptIds = [...deptIds];
  getAllTag(ids, scope.data);
  const item = !!ids.find(item => !new_deptIds.includes(item));
  if (item) {
    // 1、当前节点及其子结点包含未选中内容,选中全部当前节点及其子结点
    formValue.value.deptIds = Array.from(new Set([...ids, ...new_deptIds]));
  } else {
    // 2、当前节点及其子结点均已被选中，取消选中
    formValue.value.deptIds = new_deptIds.filter(item => !ids.includes(item));
  }
};
const handleSubmit = async formRef => {
  await formRef.validate(async valid => {
    if (valid) {
      const { id } = route.query;
      submitLoading.value = true;
      try {
        if (id) {
          await updateAnnouncement({ ...formValue.value, id });
        } else {
          await createAnnouncement({ ...formValue.value });
        }
        submitLoading.value = false;
        PxMessage.success("保存成功");
        router.push("/all/bench/task/announcement/manage");
        resetForm();
      } catch (error) {
        submitLoading.value = false;
      }
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
.form-scrollBar {
  height: calc(100vh - 290px);
}
.equip-wrap-common {
  position: static;
  height: auto;
  padding-bottom: 20px;
  margin-bottom: 68px;
}

.info-form-btns {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 68px;
  padding-right: 24px;
  background: #fff;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.option-flex-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
